function post_message(to, content) {
  var ret = null;
  if (content == "") {
    throw {
      message: gettext('empty message could not be sent')
    }
  }
  $.ajax({
    async: false,
    timeout: 3,
    type: "POST", 
    url: "/message/api/message/",
    data: {content: content, dest: to},
    success: function (msg, status) {
      ret = eval(msg)[0]; 
    },
    error: function (req, msg) {
      if (req.status == 403) {
        throw {name: 'forbidden', message: 'login required'};
      } else {
        throw {name: 'req.status', message: req.statusText};
      }
    } 
  });
  return ret;
}

$(function () {
  $("#post-message-dialog").dialog({
    autoOpen: false,
    bgiframe: true,   
    modal: true,
    width: 630, 
    open: function () {
    },
    close: function () {
      $("#post-message-dialog #hint").text("");
      $(this).find("textarea").val("");
    },
    buttons: {
      'submit': function () {
        try {
          var msg = post_message($("#post-message-dialog .username").text(), 
            $(this).children('textarea').val())
          $("#post-message-dialog #hint").text(gettext("your message sent ok!")).show("");
          $('#post-message-dialog textarea').val("");
          $('#post-message-dialog').dialog("close");
          // add to message list 
        } catch (e) {
          if (e.name == 'forbidden') {
            try_login(window.location.href, gettext("please login to send message"));
          } else {
            $("#post-message-dialog #hint").text(e.message).show();
          }
        }
      }
    }
  });
  $("#post-message-dialog").max_length({max_length: 200});
  $("#post-message-dialog textarea").keypress(function () {
      $("#post-message-dialog #hint").hide();
  });
});

function open_post_message_dialog(username) {
  $("#post-message-dialog .username").text(username);
  $("#post-message-dialog").dialog('open');
}
